<?php
/**
 * quick_curd
 * ============================================================================
 * 版权所有 2024-2099 wltx666.com，并保留所有权利。
 * 网站地址: https://wltx666.com
 * ============================================================================
 * Author: 草上飞
 * Email: wltx@alipay168.cn
 * QQ: 2719875001
 * Date: 2025/1/10
 * 描述:
 */

namespace app\result\admin;

use app\model\admin\AdminMenu;
use app\result\BaseResult;
use app\service\CurdService;
use think\facade\Db;

class CurdResult extends BaseResult
{
    private $resultPath;
    private $modelPath;
    private $controllerPath;
    private $viewPath;
    private $routePath;
    private $indexRoutePath;
    private $indexControllerPath;

    public function __construct()
    {
        parent::__construct();
        //公共
        $this->resultPath = app()->getRootPath() . '/app/result/auto/';
        $this->modelPath = app()->getRootPath() . '/app/model/auto/';
        //前端index应用
        $this->indexRoutePath = app()->getRootPath() . '/app/index/route/';
        $this->indexControllerPath = app()->getRootPath() . '/app/index/controller/auto/';
        //admin应用
        $this->controllerPath = app()->getAppPath() . '/controller/auto/';
        $this->viewPath = app()->getAppPath() . '/view/';
        $this->routePath = app()->getAppPath() . '/route/';
    }

    private function query_table_info($args): array
    {
        $table = $args['table_name'] ?? "";
        if (!$table) {
            return self::error_return('请传入表名');
        }
        //先查询表是否存在
        $table_exist = Db::query("SHOW TABLES LIKE '{$table}'");
        if (!$table_exist) {
            return self::error_return('表不存在');
        }

        $table_info = Db::query("SHOW FULL COLUMNS FROM `{$table}`");
        return self::success_return('获取成功', $table_info);
    }

    public function table_info($args): array
    {
        $forQuery = $args['for_query'] ?? false;
        if ($forQuery) {
            return self::query_table_info($args);
        }
        $table = $args['table_name'] ?? "";
        if (!$table) {
            return self::error_return('请传入表名');
        }
        //先查询表是否存在
        $table_exist = Db::query("SHOW TABLES LIKE '{$table}'");
        if (!$table_exist) {
            return self::error_return('表不存在');
        }

        // 获取表的创建语句
        $createTable = Db::query("SHOW CREATE TABLE `{$table}`");
        $tableComment = '';
        $charset = 'utf8mb4';
        $collation = 'utf8mb4_unicode_ci';

        if (!empty($createTable[0]['Create Table'])) {
            $createSql = $createTable[0]['Create Table'];

            // 提取表注释
            if (preg_match("/COMMENT='([^']+)'/", $createSql, $matches)) {
                $tableComment = $matches[1];
            }

            // 提取字符集
            if (preg_match("/CHARSET=([a-zA-Z0-9_]+)/", $createSql, $matches)) {
                $charset = $matches[1];
            }

            // 提取排序规则
            if (preg_match("/COLLATE=([a-zA-Z0-9_]+)/", $createSql, $matches)) {
                $collation = $matches[1];
            }
        }

        $table_info = Db::query("SHOW FULL COLUMNS FROM `{$table}`");

        // 处理字段信息
        $columns = [];
        foreach ($table_info as $column) {
            // 解析字段类型
            $type = $column['Type'];
            $length = '';
            $decimal = '';
            $unsigned = '';

            // 提取长度和小数点
            if (preg_match('/([a-zA-Z]+)\((\d+),(\d+)\)/', $type, $matches)) {
                $type = strtoupper($matches[1]);
                $length = $matches[2];
                $decimal = $matches[3];
            } elseif (preg_match('/([a-zA-Z]+)\((\d+)\)/', $type, $matches)) {
                $type = strtoupper($matches[1]);
                $length = $matches[2];
            } else {
                $type = strtoupper($type);
            }

            // 检查是否无符号
            if (strpos($column['Type'], 'unsigned') !== false) {
                $unsigned = 'UNSIGNED';
            }

            // 检查是否自增
            $autoIncrement = '';
            if ($column['Extra'] == 'auto_increment') {
                $autoIncrement = 'AUTO_INCREMENT';
            }

            // 检查键类型
            $key = $column['Key'];
            switch ($key) {
                case 'PRI':
                    $key = 'PRIMARY KEY';
                    break;
                case 'UNI':
                    $key = 'UNIQUE';
                    break;
                case 'MUL':
                    $key = 'INDEX';
                    break;
                default:
                    $key = '';
            }

            $columns[] = [
                'field' => $column['Field'],
                'type' => $type,
                'length' => $length,
                'decimal' => $decimal,
                'nullable' => $column['Null'] == 'NO' ? 'NOT NULL' : 'NULL',
                'key' => $key,
                'default' => $column['Default'],
                'comment' => $column['Comment'],
                'unsigned' => $unsigned,
                'autoIncrement' => $autoIncrement
            ];
        }

        return self::success_return('获取成功', [
            'table_name' => $table,
            'table_comment' => $tableComment,
            'charset' => $charset,
            'collation' => $collation,
            'columns' => $columns
        ]);
    }

    // 将字符串按下划线分割成数组，将每个单词的首字母大写，再合并成字符串
    private function toCamelCase($str)
    {
        // 将字符串按下划线分割成数组
        $arr = explode('_', $str);
        // 遍历数组，将每个单词的首字母大写
        $arr = array_map('ucfirst', $arr);
        // 将数组合并成字符串
        return implode('', $arr);
    }

    private function check_dir($tableName): array
    {
        if (!is_dir($this->resultPath)) {
            @mkdir($this->resultPath, 0775, true);
        }
        if (!is_dir($this->resultPath) || !is_writable($this->resultPath)) {
            return self::error_return($this->resultPath . '目录没有写入权限');
        }
        if (!is_dir($this->modelPath)) {
            @mkdir($this->modelPath, 0775, true);
        }
        if (!is_dir($this->modelPath) || !is_writable($this->modelPath)) {
            return self::error_return($this->modelPath . '目录没有写入权限');
        }
        if (!is_dir($this->controllerPath)) {
            @mkdir($this->controllerPath, 0775, true);
        }
        if (!is_dir($this->controllerPath) || !is_writable($this->controllerPath)) {
            return self::error_return($this->controllerPath . '目录没有写入权限');
        }
        if (!is_dir($this->viewPath . $tableName)) {
            @mkdir($this->viewPath . $tableName, 0775, true);
        }
        if (!is_dir($this->viewPath . $tableName) || !is_writable($this->viewPath . $tableName)) {
            return self::error_return($this->viewPath . $tableName . '目录没有写入权限');
        }
        if (!is_dir($this->indexControllerPath)) {
            @mkdir($this->indexControllerPath, 0775, true);
        }
        if (!is_writable($this->indexControllerPath)) {
            return self::error_return($this->indexControllerPath . '目录没有写入权限');
        }
        if (!is_writable($this->routePath)) {
            return self::error_return($this->routePath . '目录没有写入权限');
        }
        if (!is_dir($this->indexRoutePath)) {
            @mkdir($this->indexRoutePath, 0775, true);
        }
        if (!is_writable($this->indexRoutePath)) {
            return self::error_return($this->indexRoutePath . '目录没有写入权限');
        }
        return self::success_return('检查目录权限成功');
    }

    // 创建数据表
    public function create_table($args): array
    {
        $overwrite = $args['overwrite'] ?? false; // 是否覆盖
        $tableName = $args['tableName'] ?? "";
        $tableComment = $args['tableComment'] ?? "";
        $charset = $args['charset'] ?? "utf8mb4";
        $collation = $args['collation'] ?? "utf8mb4_unicode_ci";
        $columns = $args['columns'] ?? [];

        if (!$tableName) {
            return self::error_return('请传入数据表名');
        }

        if (!$columns) {
            return self::error_return('请传入字段');
        }

        // 检查表是否已存在
        $tableExists = Db::query("SHOW TABLES LIKE '{$tableName}'");
        if ($tableExists && !$overwrite) {
            return self::error_return('已存在同名表名，是否覆盖？', [], -100);
        }

        // 构建创建表的SQL语句
        $sql = "CREATE TABLE IF NOT EXISTS `{$tableName}` (";

        $hasPrimaryKey = false;
        $primaryKey = '';
        $fieldsSql = [];

        foreach ($columns as $column) {
            $field = $column['field'] ?? '';
            $type = $column['type'] ?? '';
            $length = $column['length'] ?? '';
            $decimal = $column['decimal'] ?? '';
            $nullable = $column['nullable'] ?? 'NULL';
            $key = $column['key'] ?? '';
            $default = $column['default'] ?? '';
            $comment = $column['comment'] ?? '';
            $unsigned = $column['unsigned'] ?? '';
            $autoIncrement = $column['autoIncrement'] ?? '';

            if (!$field || !$type) {
                continue;
            }

            $fieldSql = "`{$field}` {$type}";

            // 添加长度和小数点
            if ($length) {
                if ($decimal) {
                    $fieldSql .= "({$length}, {$decimal})";
                } else {
                    $fieldSql .= "({$length})";
                }
            }

            // 添加无符号属性
            if ($unsigned) {
                $fieldSql .= " {$unsigned}";
            }

            // 添加NULL/NOT NULL
            $fieldSql .= " {$nullable}";

            // 添加默认值
            if ($default !== '') {
                if (strtoupper($default) === 'NULL') {
                    $fieldSql .= " DEFAULT NULL";
                } else {
                    $fieldSql .= " DEFAULT '{$default}'";
                }
            }

            // 添加自增属性
            if ($autoIncrement) {
                $fieldSql .= " {$autoIncrement}";
            }

            // 添加注释
            if ($comment) {
                $fieldSql .= " COMMENT '{$comment}'";
            }

            $fieldsSql[] = $fieldSql;

            // 检查是否有主键
            if ($key === 'PRIMARY KEY') {
                $primaryKey = $field;
                $hasPrimaryKey = true;
            }
        }

        // 添加字段定义
        $sql .= implode(', ', $fieldsSql);

        // 添加主键
        if ($hasPrimaryKey) {
            $sql .= ", PRIMARY KEY (`{$primaryKey}`)";
        }

        // 添加表选项
        $sql .= ") ENGINE=InnoDB DEFAULT CHARSET={$charset} COLLATE={$collation}";

        // 添加表注释
        if ($tableComment) {
            $sql .= " COMMENT='{$tableComment}'";
        }

        // 如果表存在且需要覆盖，则先删除表
        if ($tableExists && $overwrite) {
            Db::execute("DROP TABLE IF EXISTS `{$tableName}`");
        }

        // 执行创建表语句
        try {
            Db::execute($sql);
            return self::success_return('创建成功');
        } catch (\Exception $e) {
            return self::error_return('创建失败: ' . $e->getMessage());
        }
    }

    // 修改数据表结构
    public function edit_table($args): array
    {
        $tableName = $args['tableName'] ?? "";
        $tableComment = $args['tableComment'] ?? "";
        $charset = $args['charset'] ?? "utf8mb4";
        $collation = $args['collation'] ?? "utf8mb4_unicode_ci";
        $columns = $args['columns'] ?? [];
        $deletedColumns = $args['deletedColumns'] ?? [];

        if (!$tableName) {
            return self::error_return('请传入数据表名');
        }

        if (!$columns) {
            return self::error_return('请传入字段');
        }

        // 开始事务处理
        Db::startTrans();
        try {
            // 1. 删除字段
            foreach ($deletedColumns as $deletedColumn) {
                $field = $deletedColumn['field'] ?? '';
                if ($field) {
                    $sql = "ALTER TABLE `{$tableName}` DROP COLUMN `{$field}`";
                    Db::execute($sql);
                }
            }

            // 2. 修改或添加字段
            foreach ($columns as $column) {
                $field = $column['field'] ?? '';
                $type = $column['type'] ?? '';
                $length = $column['length'] ?? '';
                $decimal = $column['decimal'] ?? '';
                $nullable = $column['nullable'] ?? 'NULL';
                $key = $column['key'] ?? '';
                $default = $column['default'] ?? '';
                $comment = $column['comment'] ?? '';
                $unsigned = $column['unsigned'] ?? '';
                $autoIncrement = $column['autoIncrement'] ?? '';
                $after = $column['after'] ?? '';

                if (!$field || !$type) {
                    continue;
                }

                // 构建字段类型
                $fieldType = "{$type}";
                if ($length) {
                    if ($decimal) {
                        $fieldType .= "({$length}, {$decimal})";
                    } else {
                        $fieldType .= "({$length})";
                    }
                }
                if ($unsigned) {
                    $fieldType .= " {$unsigned}";
                }

                // 构建ALTER语句
                $sql = "ALTER TABLE `{$tableName}` ";

                // 检查字段是否已存在
                $columnExists = Db::query("SHOW COLUMNS FROM `{$tableName}` LIKE '{$field}'");

                if ($columnExists) {
                    // 修改字段
                    $sql .= "MODIFY COLUMN `{$field}` {$fieldType} {$nullable}";
                } else {
                    // 添加字段
                    $sql .= "ADD COLUMN `{$field}` {$fieldType} {$nullable}";
                    if ($after) {
                        $sql .= " AFTER `{$after}`";
                    }
                }

                // 添加默认值
                if ($default !== '') {
                    if (strtoupper($default) === 'NULL') {
                        $sql .= " DEFAULT NULL";
                    } else {
                        $sql .= " DEFAULT '{$default}'";
                    }
                } elseif ($nullable === 'NOT NULL' && !$autoIncrement) {
                    // 对于NOT NULL字段且非自增字段，如果没有默认值，需要指定一个默认值
                    if (in_array($type, ['VARCHAR', 'CHAR', 'TEXT'])) {
                        $sql .= " DEFAULT ''";
                    } elseif (in_array($type, ['INT', 'TINYINT', 'SMALLINT', 'MEDIUMINT', 'BIGINT'])) {
                        $sql .= " DEFAULT 0";
                    } elseif (in_array($type, ['FLOAT', 'DOUBLE', 'DECIMAL'])) {
                        $sql .= " DEFAULT 0.00";
                    }
                }

                // 添加自增属性
                if ($autoIncrement) {
                    $sql .= " {$autoIncrement}";
                }

                // 添加注释
                if ($comment) {
                    $sql .= " COMMENT '{$comment}'";
                }

                Db::execute($sql);
            }

            // 3. 更新表选项（字符集、排序规则、注释）
            $sql = "ALTER TABLE `{$tableName}` ";
            $options = [];

            // 字符集和排序规则
            $options[] = "DEFAULT CHARSET={$charset}";
            $options[] = "COLLATE={$collation}";

            // 表注释
            if ($tableComment) {
                $options[] = "COMMENT='{$tableComment}'";
            }

            $sql .= implode(' ', $options);
            Db::execute($sql);

            // 提交事务
            Db::commit();
            return self::success_return('修改成功');
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return self::error_return('修改失败: ' . $e->getMessage());
        }
    }


    public function save_data($args): array
    {
        //bs_log($args, 'save_data', 'curd.log');
        $overwrite = $args['overwrite'] ?? false;//是否覆盖
        $tableName = $args['tableName'] ?? "";
        $admin_apis = $args['admin_apis'] ?? [];//后台接口
        $apis = $args['apis'] ?? [];//前端接口
        $menu_name = $args['menu_name'] ?? "";
        $isCreatePermission = !empty($args['isCreatePermission']);
        $api_user_id = !empty($args['api_user_id']);
        $api_need_login = !empty($args['api_need_login']);
        if (!$tableName) {
            return self::error_return('请传入数据表名');
        }
        if ($isCreatePermission) {
            if (!$menu_name) {
                return self::error_return('请传入菜单名称');
            }
            if (!$admin_apis) {
                return self::error_return('设置权限后台接口配置至少选一项');
            }

        }
        $columns = $args['columns'] ?? [];
        if (!$columns) {
            return self::error_return('请传入字段');
        }
        $table_info = Db::query("SHOW FULL COLUMNS FROM `{$tableName}`");
        if (!$table_info) {
            return self::error_return('表不存在');
        }
        //查询自增ID
        $autoIncrementId = 'id';
        foreach ($table_info as $item) {
            if (strtolower($item['Extra']) == 'auto_increment') {
                $autoIncrementId = $item['Field'];
            }
        }
        //设置自增ID字段
        CurdService::set_auto_increment_field($autoIncrementId);

        $searchFields = [];

        $tableFields = [];
        $formFields = [];
        $formMake = false;//是否生成表单
        $needUploadComponent = false;
        if (in_array('save_data', $admin_apis) || in_array('edit_data', $admin_apis)) {
            $formMake = true;
        }
        $searchWhereStr = '';
        foreach ($columns as $item) {
            if ($formMake && !in_array($item['Field'], [$autoIncrementId, 'created_at', 'updated_at', 'is_delete', 'deleted_at', 'del_time'])) {
                $f = [
                    'field' => $item['Field'],
                    'label' => $item['ShowListDisplayName'] ?: ($item['Comment'] ?: $item['Field']),
                    'isEditable' => $item['isEditable'],
                    'isRequired' => $item['isRequired'],
                    'componentType' => $item['componentType'],
                    'optionsSource' => $item['optionsSource'],
                ];
                if (in_array($item['componentType'], ['upload-image', 'upload-file'])) {
                    $needUploadComponent = true;
                }
                if ($item['componentType'] == 'select') {
                    $f['options'] = $item['options'];
                }
                $formFields[] = $f;
            }

            if ($item['isSearchable']) {
                //搜索条件

                if ($item['componentType'] == 'daterange') {
                    $searchWhereStr .= "
                    if (!empty(\$args['{$item['Field']}'])) {
                    \$where[] = ['{$item['Field']}', 'between', [\$args['{$item['Field']}'][0].' 00:00:00', \$args['{$item['Field']}'][1].' 23:59:59']];
                    }";

                } else {
                    $searchWhereStr .= "
                if (!empty(\$args['{$item['Field']}'])) {
                    \$where[] = ['{$item['Field']}', '=', \$args['{$item['Field']}']];
                }";
                }
                $s = [
                    'name' => $item['Field'],
                    'label' => $item['ShowListDisplayName'],
                    'type' => $item['componentType'],
                    'placeholder' => $item['searchDisplayName']
                ];
                if ($item['componentType'] == 'select') {
                    $s['options'] = $item['options'];
                }
                $searchFields[] = $s;
            }
            if ($item['isShowList']) {
                $tmp = [
                    'prop' => $item['Field'],
                    'type' => 'text',
                    'label' => $item['ShowListDisplayName'],
                    'minWidth' => 120,
                    'align' => 'center',
                ];
                if ($item['componentType'] == 'select') {
                    $tmp['type'] = 'tags';
                    $tmp['tags'] = [];
                    foreach ($item['options'] as $option) {
                        $tmp['tags'][$option['value']] = [
                            'label' => $option['label'],
                            'value' => $option['value'],
                            'color' => '',
                            'type' => 'success',
                        ];
                    }
                } elseif ($item['componentType'] == 'image' || $item['Field'] == 'image' || $item['Field'] == 'images') {
                    $tmp['type'] = 'image';
                }
                $tableFields[] = $tmp;
            }
        }

        $actionButtons = [];
        if (in_array('edit_data', $admin_apis)) {
            $actionButtons[] = ['edit' => ['label' => '编辑', 'action' => 'edit', 'icon' => 'el-icon-edit', 'type' => 'success', 'size' => 'mini',]];
        }
        if (in_array('del_data', $admin_apis)) {
            $actionButtons[] = ['del' => ['label' => '删除', 'action' => 'del', 'icon' => 'el-icon-delete', 'type' => 'danger', 'size' => 'mini',]];
        }
        if ($actionButtons) {
            $tableFields[] = [
                'prop' => '', 'type' => 'buttons', 'label' => '编辑', 'minWidth' => 130, 'align' => 'center', 'fixed' => 'right',
                'buttons' => $actionButtons
            ];
        }

        $prefix = config('database.prefix');
        if ($prefix) {
            $tableName = substr($tableName, strlen($prefix));
        }

        $className = $this->toCamelCase($tableName);
        $checkDir = $this->check_dir($tableName);
        if ($checkDir['code'] != 0) {
            return $checkDir;
        }
        $resultPath = $this->resultPath . $className . 'Result.php';
        if (file_exists($resultPath) && !$overwrite) {
            return self::error_return('文件其存在，是否强制覆盖？', [], -100);
        }
        $tplResult = CurdService::tpl_result([
            'className' => $className . 'Result',
            'modelName' => $className,
            'tableFields' => $tableFields,
            'searchFields' => $searchFields,
            'searchWhereStr' => $searchWhereStr,
            'formFields' => $formFields,
            'admin_apis' => $admin_apis,
            'apis' => $apis,
            'need_user_id' => $api_user_id,
        ]);
        file_put_contents($resultPath, $tplResult);
        $tplModel = CurdService::tpl_model([
            'modelName' => $className,
        ]);
        $modelPath = $this->modelPath . $className . '.php';
        file_put_contents($modelPath, $tplModel);
        //是否需要后端控制器
        if (!empty($admin_apis)) {
            $controllerPath = $this->controllerPath . $className . '.php';
            $tplController = CurdService::tpl_admin_controller([
                'className' => $className,
                'tableName' => $tableName,
                'resultName' => $className . 'Result',
                'admin_apis' => $admin_apis,
            ]);
            file_put_contents($controllerPath, $tplController);
            $routePath = $this->routePath . 'admin_' . strtolower($tableName) . '.php';
            $tplRoute = CurdService::tpl_admin_route([
                'group' => strtolower($tableName),
                'className' => $className,
                'admin_apis' => $admin_apis
            ]);
            file_put_contents($routePath, $tplRoute);

            //创建权限菜单
            if ($isCreatePermission) {
                $this->create_auth_menu($menu_name, $admin_apis, $tableName, $args);
            }

            //生成管理后台前端文件
            $this->make_admin_front_file([
                'tableName' => $tableName,
                'admin_apis' => $admin_apis,
                'auto_increment_id' => $autoIncrementId,
                'menu_name' => $menu_name,
                'form_fields' => $formFields,
                'needUploadComponent' => $needUploadComponent
            ]);
        }
        // return self::success_return('生成成功');
        //是否需要前端控制器
        if (!empty($apis)) {
            //前端控制器
            $controllerPath = $this->indexControllerPath . $className . '.php';
            $tplController = CurdService::tpl_front_controller([
                'className' => $className,
                'resultName' => $className . 'Result',
                'apis' => $apis,
                'need_user_id' => $api_user_id,
                'need_login' => $api_need_login
            ]);
            file_put_contents($controllerPath, $tplController);
            //前端路由
            $routePath = $this->indexRoutePath . 'index_' . strtolower($tableName) . '.php';
            //bs_log($routePath,'debug','rrr.log');
            $tplRoute = CurdService::tpl_front_route([
                'group' => strtolower($tableName),
                'className' => $className,
                'apis' => $apis,
            ]);
            file_put_contents($routePath, $tplRoute);
        }

        return self::success_return('生成成功');
    }


    //生成管理后台前端文件
    private function make_admin_front_file($args)
    {
        $tableName = $args['tableName'];
        $menu_name = $args['menu_name'] ?: "管理后台";
        $admin_apis = $args['admin_apis'];
        $formFields = $args['form_fields'];
        $needUploadComponent = $args['needUploadComponent'];
        $auto_increment_id = $args['auto_increment_id'];
        $tpl_admin_index = file_get_contents(app()->getRootPath() . '/app/result/admin/tpl/admin_index.tpl');
        $tpl_admin_index = str_replace('$bs_table_name', $tableName, $tpl_admin_index);
        $tpl_admin_index = str_replace('$menu_title', $menu_name, $tpl_admin_index);
        $tpl_admin_index = str_replace('$auto_increment_id', $auto_increment_id, $tpl_admin_index);
        if (in_array('save_data', $admin_apis)) {
            $tpl_admin_index = str_replace('<!--<hook_add_button-->', '<!--<hook_add_button-->' . PHP_EOL . '<el-button  type="success" size="mini" icon="el-icon-plus" @click="add">新增</el-button>', $tpl_admin_index);
        }
        //上传组件
        if ($needUploadComponent) {
            $tpl_admin_index = str_replace('<!--hook_upload_m-->', '<!-- 引入上传方法$upload_m.js -->' . PHP_EOL . '<script src="/static/js/upload_m.js?t=' . time() . '"></script>', $tpl_admin_index);
            $tpl_admin_index = str_replace('//<hook_upload_m>', 'Vue.mixin(upload_m);', $tpl_admin_index);
        }
        if ($formFields) {
            $fileColumns = array_column($formFields, 'field');
            //把id放到最上面
            array_unshift($fileColumns, 'id');
            $form = [];
            foreach ($fileColumns as $fileColumn) {
                $form[$fileColumn] = '';
            }
            $tpl_admin_index = str_replace('//<hook_form_filed>', 'form:' . json_encode($form), $tpl_admin_index);
        }

        //todo 表单生成
        //直接生成index.html入口，这个是mvc的哈
        file_put_contents($this->viewPath . $tableName . '/index.html', $tpl_admin_index);
    }

    //生成菜单
    private function create_auth_menu($menu_name, $admin_apis, $tableName)
    {
        //核心的菜单不需要就跳过
        if (!in_array('list', $admin_apis) && !in_array('get', $admin_apis)) {
            return true;
        }
        $parentData = [
            'type' => 0,//类型：0=菜单-页面；1=功能-权限
            'parent_id' => 0,
            'path' => "$tableName/index",
            'title' => $menu_name,
            'icon' => 'el-icon-menu',
            'hidden' => 0,
        ];
        $result = new MenusResult();
        $res = $result->quick_add($parentData);
        if ($res['code'] <> 0) {
            return self::error_return('创建菜单失败:' . $res['msg']);
        }
        $matchRoute = [
            'list' => ['name' => '数据列表', 'route' => 'list'],
            'list_config' => ['name' => '列表配置', 'route' => 'list_config'],
            'get' => ['name' => '详情', 'route' => 'get'],
            'save_data' => ['name' => '新增', 'route' => 'save'],
            //'edit_data' => ['name' => '修改', 'route' => 'save'],
            'del_data' => ['name' => '删除', 'route' => 'delete'],
            'list_options' => ['name' => '下拉选项', 'route' => 'list_options'],
            'status' => ['name' => '快速修改状态', 'route' => 'status'],
        ];
        $menu_id = $res['data']['id'];
        $baseData = [];
        foreach ($admin_apis as $api) {
            if (!isset($matchRoute[$api])){
                continue;
            }
            $baseData[] = [
                'type' => 1,//类型：0=菜单-页面；1=功能-权限
                'parent_id' => $menu_id,
                'path' => "$tableName/" . $matchRoute[$api]['route'],
                'title' => $matchRoute[$api]['name'],
                'icon' => 'el-icon-menu',
                'hidden' => 1,
            ];
        }
        if ($baseData) {
            (new AdminMenu())->allowField(['parent_id', 'path', 'title', 'icon', 'hidden', 'sort', 'type'])->saveAll($baseData);
        }
        return true;
    }

}
